package me.zingon.yourbatis.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DBPool implements IDBPool {

    List<DBConnection> connectionPool;

    public DBPool(String driver,int poolSize, String url, String user, String password) throws ClassNotFoundException {
        connectionPool = Collections.synchronizedList(new ArrayList<DBConnection>());
        Class.forName(driver);
        for (int i = 0; i < poolSize; i++) {
            try {
                Connection con = DriverManager.getConnection(url, user, password);
                connectionPool.add(new DBConnection(con));
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public DBConnection getConnection() throws Exception {
        for (int i = connectionPool.size() - 1; i >= 0; i--) {
            if(connectionPool.get(i).getConnection() != null){
                return connectionPool.get(i);
            }
        }
        throw new Exception("数据库连接池全部busy");
    }
}
